package com.hsq.ndmall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hsq.ndmall.common.utils.R;
import com.hsq.ndmall.product.entity.GoodsEntity;
import com.hsq.ndmall.product.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.hsq.ndmall.product.dao.CategoryDao;
import com.hsq.ndmall.product.entity.CategoryEntity;
import com.hsq.ndmall.product.service.CategoryService;
import com.hsq.ndmall.common.utils.PageUtils;
import com.hsq.ndmall.common.utils.Query;

@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    CategoryDao categoryDao;

    @Autowired
    private GoodsService goodsService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                getQueryWrapper(params)
        );

        return new PageUtils(page);
    }

    /**
     * 自定义了一个接口  用来返回一级分类
     *
     * @return
     */
    @Override
    public R findTopCategory() {
        R r = new R();
        r.put("channel", categoryDao.findTopCategory());
        return r;
    }


    @Override
    public PageUtils getCategory2GoodsList(Integer page, Integer limit) {
        List<Map> categoryList = new ArrayList<>();
        // 分页查询类目为一级分类的
        PageUtils pageUtils = queryL1WithoutRecommend((page - 1), limit);
        /*
        * CategoryEntity(id=1005000, name=居家, keywords=, desc=回家，放松身心, pid=0, iconUrl=http://yanxuan.nosdn.127.net/a45c2c262a476fea0b9fc684fed91ef5.png, picUrl=http://yanxuan.nosdn.127.net/e8bf0cf08cf7eda21606ab191762e35c.png, level=L1, sortOrder=2, addTime=Thu Feb 01 00:00:00 CST 2018, updateTime=Thu Feb 01 00:00:00 CST 2018, deleted=false)
        *   1 = {CategoryEntity@9975} "CategoryEntity(id=1005001, name=餐厨, keywords=, desc=爱，囿于厨房, pid=0, iconUrl=http://yanxuan.nosdn.127.net/ad8b00d084cb7d0958998edb5fee9c0a.png, picUrl=http://yanxuan.nosdn.127.net/3708dbcb35ad5abf9e001500f73db615.png, level=L1, sortOrder=3, addTime=Thu Feb 01 00:00:00 CST 2018, updateTime=Thu Feb 01 00:00:00 CST 2018, deleted=false)"
            2 = {CategoryEntity@9976} "CategoryEntity(id=1005002, name=饮食, keywords=, desc=好吃，高颜值美食, pid=0, iconUrl=http://yanxuan.nosdn.127.net/c9280327a3fd2374c000f6bf52dff6eb.png, picUrl=http://yanxuan.nosdn.127.net/fb670ff3511182833e5b035275e4ac09.png, level=L1, sortOrder=9, addTime=Thu Feb 01 00:00:00 CST 2018, updateTime=Thu Feb 01 00:00:00 CST 2018, deleted=false)"
            3 = {CategoryEntity@9977} "CategoryEntity(id=1008000, name=配件, keywords=, desc=配角，亦是主角, pid=0, iconUrl=http://yanxuan.nosdn.127.net/11abb11c4cfdee59abfb6d16caca4c6a.png, picUrl=http://yanxuan.nosdn.127.net/02f9a44d05c05c0dd439a5eb674570a2.png, level=L1, sortOrder=4, addTime=Thu Feb 01 00:00:00 CST 2018, updateTime=Thu Feb 01 00:00:00 CST 2018, deleted=false)"
        * */
        // 遍历一级分类信息  循环四次
        for (CategoryEntity catL1 : (List<CategoryEntity>) pageUtils.getList()) {
            // 根据一级类目ID信息去查询子类，例如查询的是居家，则查询居家的二级类目（布艺软装、被枕、灯具、床垫。。。。）
            List<CategoryEntity> catL2List = queryByPid(catL1.getId());
            // 新建一个Integer集合，存放二级类目的ID
            List<Integer> l2List = new ArrayList<>();
            for (CategoryEntity catL2 : catL2List) {
                l2List.add(catL2.getId());
            }
            // 新建一个Goods集合，存放商品信息
            List<GoodsEntity> categoryGoods;
            if (l2List.size() == 0) {
                categoryGoods = new ArrayList<>();
            } else {
                synchronized (this) {
                    // 根据二级类目ID查询商品信息
                    categoryGoods = goodsService.queryByCategory(l2List, 1, 4);
                }
            }

            Map<String, Object> catGoods = new HashMap<>();
            catGoods.put("id", catL1.getId());
            catGoods.put("name", catL1.getName());
            catGoods.put("goodsList", categoryGoods);
            categoryList.add(catGoods);
        }
        //替换原来的商品分类为楼层集合
        pageUtils.setList(categoryList);
        return pageUtils;
    }


    private PageUtils queryL1WithoutRecommend(int offset, int limit) {
        Page<CategoryEntity> page = categoryDao.selectPage(new Page<>(offset, limit), Wrappers.<CategoryEntity>lambdaQuery()
                .eq(CategoryEntity::getLevel, "L1")
                .eq(CategoryEntity::getDeleted, false)
        );
        return new PageUtils(page);
    }

    /**
     * 条件查询
     *
     * @param params
     * @return
     */
    private QueryWrapper getQueryWrapper(Map<String, Object> params) {
        QueryWrapper<CategoryEntity> queryWrapper = new QueryWrapper<>();
        // 查询一级分类
        if (params.containsKey("level")) {
            queryWrapper.lambda().eq(CategoryEntity::getLevel, params.containsKey("level"));
        }
        // 分类主页要默认查询居家
        if (params.containsKey("id")) {
            queryWrapper.lambda().eq(CategoryEntity::getId, params.get("id"));
        }
        if (params.containsKey("pid")) {
            queryWrapper.lambda().eq(CategoryEntity::getPid, params.get("pid"));
        }
        if (params.containsKey("brother_id")) {
            CategoryEntity categoryEntity = categoryDao.selectOne(new QueryWrapper<CategoryEntity>().lambda().eq(CategoryEntity::getId, params.get("brother_id")));
            queryWrapper.lambda().eq(CategoryEntity::getPid,categoryEntity.getPid());
        }
        if (params.containsKey("parent_id")) {
            CategoryEntity categoryEntity = categoryDao.selectOne(new QueryWrapper<CategoryEntity>().lambda().eq(CategoryEntity::getId, params.get("parent_id")));
            queryWrapper.lambda().eq(CategoryEntity::getId,categoryEntity.getPid());
        }

        return queryWrapper;
    }

    /**
     * 通过一级分类Id查询出子分类
     *
     * @param pid
     * @return
     */
    private List<CategoryEntity> queryByPid(Integer pid) {
        return categoryDao.selectList(Wrappers.<CategoryEntity>lambdaQuery().eq(CategoryEntity::getPid, pid).eq(CategoryEntity::getDeleted, false));
    }

}
